package com.ygqh.baby.service.task.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.foxinmy.weixin4j.mp.api.NotifyApi;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.tuple.News;
import com.ygqh.baby.ao.MsgType;
import com.ygqh.baby.ao.TaskMethod;
import com.ygqh.baby.po.WxCustomMsgDetail;
import com.ygqh.baby.service.WxCustomMsgDetailService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgTaskTimeService;
import com.ygqh.baby.service.YgWeixinMenuDayService;
import com.ygqh.baby.service.task.WxMsgTaskService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.MailUtil;

@Service
public class WxMsgTaskServiceImpl implements WxMsgTaskService {

	protected final Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private YgTaskTimeService ygTaskTimeService;
	@Autowired
	private YgWeixinMenuDayService ygWeixinMenuDayService;
	@Autowired
	private WxCustomMsgDetailService wxCustomMsgDetailService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private MailUtil mailUtil;

	@Override
	public void sendCustomerNewsMsg() {
		System.out.println("发送微信客服图文消息任务启动");
		Date runTime = new Date();
		try {
			menuFrom48Hour(runTime);
			ygTaskTimeService.saveOrUpdate(TaskMethod.SendCustomerNewsMsg.name(), runTime, "【发送微信客服图文消】执行成功");
		} catch (Exception e) {
			ygTaskTimeService.saveOrUpdate(TaskMethod.SendCustomerNewsMsg.name(), runTime, "【发送微信客服图文消】执行失败；" + ExceptionUtil.getExceptionMsg(e));
			try {
				mailUtil.sendWithHtml(new String[]{"sunshuo@yiigoo.cn"}, "发送微信客服图文消息任务", ExceptionUtil.getExceptionMsg(e));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		System.out.println("发送微信客服图文消息任务结束");
	}

	protected void menuFrom48Hour(Date runTime) {
		List<WxCustomMsgDetail> msgList = wxCustomMsgDetailService.findBySendDateAndType(runTime, MsgType.News);
		if (CollectionUtils.isEmpty(msgList)) {
			logger.warn("当天没有可发送的微信客服消息");
			return;
		}
		logger.info("当天的微信客服消息数：" + msgList.size());
		Date startDate = DateConvertUtils.addDay(runTime, -2);
		List<String> openIdList = ygWeixinMenuDayService.getOpenId(startDate);
		if (CollectionUtils.isEmpty(openIdList)) {
			logger.warn("48小时内无用户访问");
			return;
		}
		logger.info("48小时内访问用户数：" + openIdList.size());
		String sourceCode = DateConvertUtils.format(runTime, "yyyyMMdd");
		sendMsg(openIdList, msgList, sourceCode);
	}

	protected void sendMsg(List<String> openIdList, List<WxCustomMsgDetail> msgList, String sourceCode) {
		News news = new News();
		for (int i = 0; i < msgList.size(); i++) {
			if (i == 5) {
				break;
			}
			WxCustomMsgDetail detail = msgList.get(i);
			String msgLinkUrl = detail.getMsgLinkUrl();
			if (msgLinkUrl.indexOf("?") != -1) {
				msgLinkUrl = msgLinkUrl + "&sourceCode=" + sourceCode;
			} else {
				msgLinkUrl = msgLinkUrl + "?sourceCode=" + sourceCode;
			}
			news.addArticle(detail.getMsgTitle(), null, detail.getMsgImagePath(), msgLinkUrl);
		}
		sendMsg(openIdList, news);
	}

	private void sendMsg(List<String> openIdList, News news) {
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
		for (String openId : openIdList) {
			fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					NotifyMessage notifyMessage = new NotifyMessage(openId, news);
					NotifyApi notifyAPI = new NotifyApi(wxMpAuthorityService.findTokenHolder());
					try {
						notifyAPI.sendNotify(notifyMessage);
					} catch (Exception e) {
						e.printStackTrace();
						if (!e.getMessage().contains("45015")) {
							logger.warn("发送微信客服消息失败openId:" + openId + ", " + ExceptionUtil.getExceptionMsg(e));
						}
					}
				}
			});
		}
      fixedThreadPool.shutdown();
	}

}
